import PropTypes from 'prop-types';
import React from 'react';
import { message } from 'antd';
import { API_HOST } from 'Constants/config';
import Api from 'Utils/api';
import './index.scss';

/**
 * 视频上传组件
 * 需要Form包裹来使用
 */
class UploadAudio extends React.PureComponent {
  static propTypes = {
    value: PropTypes.number,
    onChange: PropTypes.func,
  }
  static defaultProps = {
    value: 0,
    onChange: () => {},
  }
  constructor(props) {
    super(props);
    this.state = {
      resourceId: props.value,
    };
    this.uploadInput = undefined;
    this.audioRef = undefined;
    this.UploadAudio = ::this.UploadAudio;
  }
  componentWillReceiveProps(nextProps) {
    this.setState({ resourceId: nextProps.value });
  }
  UploadAudio() {
    const { onChange } = this.props;
    const file = this.uploadInput.files[0];
    if (!file) {
      return;
    }
    const formData = new window.FormData();
    formData.append('upload_file', file);
    const self = this;
    const api = new Api({
      method: 'POST',
      path: '/files',
      noHeader: true,
      data: formData,
      success: (json) => {
        self.setState({ resourceId: json.id }, () => {
          onChange(json.id);
          if (this.audioRef) {
            this.audioRef.src = `${API_HOST}/files/${json.id}`;
          }
        });
      },
      error: (msg) => {
        message.error(msg);
      },
    });
    api.run();
  }
  render() {
    const { resourceId } = this.state;
    return (
      <div className="upload-audio-container">
        <input
          ref={(ref) => { this.uploadInput = ref; }}
          type="file"
          accept="audio/*"
          onChange={this.UploadAudio.bind(this)}
        />
        <img src="images/dispatch/icon_add.png" alt="添加" />
        {resourceId > 0 &&
        <audio
          ref={(ref) => { this.audioRef = ref; }}
          controls
          preload
          style={{ width: 640 }}
        >
          <source src={`${API_HOST}/files/${resourceId}`} type="audio/webm" />
        </audio>
        }
      </div>
    );
  }
}

export default UploadAudio;
